﻿namespace YunQue.WebApi.Controllers
{
    /// <summary>
    /// 登录接口
    /// </summary>
    [ApiExplorerSettings(GroupName = "login")]
    public class LoginController : BaseController
    {
        private readonly LoginService _loginService;

        private readonly UserService _userService;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="loginService"></param>
        ///  <param name="userService"></param>
        public LoginController(LoginService loginService, UserService userService)
        {
            _loginService = loginService;
            _userService = userService;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("login")]
        [AllowAnonymous]
        public async Task<LoginResult> LoginAsync([FromBody] LoginModelRequest request)
        {
            var tenantCode = RASEncryption.Decrypt(request.TenantCode);
            var user = await _loginService.GetUserWithLoginAsync(request.UserName, request.Password);
            string sessionId = Guid.NewGuid().ToString();
            var token = JwtHelper.CreateToken(user, tenantCode, sessionId);
            //7天有效期
            await RedisWrapper.SetAsync(sessionId, true, TimeSpan.FromDays(7));
            return await Task.FromResult(new LoginResult() { Now = DateTime.Now, Token = token });
        }
        /// <summary>
        /// 获取登录用户的信息
        /// </summary>
        /// <returns></returns>
        [HttpGet("getInfo")]
        public async Task<UserInfo> GetInfoAsync()
        {
            var id = _userContext.Id;
            if(string.IsNullOrEmpty(id)) throw new Exception("用户未登录");
            return await _userService.GetUserByIdAsync(id);
        }
        /// <summary>
        /// 登出
        /// </summary>
        /// <returns></returns>
        [HttpPost("logout")]
        public async Task<bool> LogOutAsync()
        {
            //清除登录状态
            await RedisWrapper.RemoveAsync(_userContext.SessionId);
            return await Task.FromResult(true);
        }
        /// <summary>
        /// 刷新token
        /// </summary>
        /// <returns></returns>
        [HttpGet("refresh-token")]
        public async Task<string> RefreshTokenAsync()
        {
            var user = await _userService.GetUserByIdAsync(_userContext.Id);
            var oldSessionId = _userContext.SessionId;
            string sessionId = Guid.NewGuid().ToString();
            var token = JwtHelper.CreateToken(user, user.TenantCode, sessionId);
            //7天有效期
            await RedisWrapper.RemoveAsync(oldSessionId);
            await RedisWrapper.SetAsync(sessionId, true, TimeSpan.FromDays(7));
            return await Task.FromResult(token);
        }


    }
}
